package com.nba.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.nba.bean.Team;
import com.nba.dao.PartitionDao;
import com.nba.dao.UnionDao;
import com.nba.dao.impl.PartitionDaoImpl;
import com.nba.dao.impl.UnionDaoImpl;
import com.nba.service.TeamService;
import com.nba.service.impl.TeamServiceImpl;

@WebServlet("/TeamServlet.do")
public class TeamServlet extends HttpServlet{
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String opt = request.getParameter("opt");
		switch(opt) {
			case "0":
				delete(request,response);
				break;
			case "1":
				add(request,response);
				break;
			case "2":
				deleteAll(request,response);
				break;
			case "3":
				update(request,response);
				break;
			case "4":
				search(request,response);
				break;
		}
	}
	
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TeamService teamservice = new TeamServiceImpl();
		int teamId = Integer.parseInt(request.getParameter("teamId"));
		teamservice.deleteTeam(teamId);
		response.sendRedirect("SearchServlet.do");
	}
	public void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TeamService teamservice = new TeamServiceImpl();
		String ids = request.getParameter("ids");
		if(ids!=null) {
			String[] idArray = ids.split("_");
			for (int i = 0; i < idArray.length; i++) {
				teamservice.deleteTeam(Integer.parseInt(idArray[i]));
			}
		}
	}
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TeamService ts = new TeamServiceImpl();
		int teamId = Integer.parseInt(request.getParameter("teamId"));
		FileItemFactory itemFactory = new DiskFileItemFactory();//鍒涘缓涓�涓笂浼犳枃浠跺伐鍘傜被
		ServletFileUpload upload = new ServletFileUpload(itemFactory); //鍒涘缓涓�涓� 鏂囦欢涓婁紶 鏍稿績瀵硅薄
		upload.setHeaderEncoding("UTF-8"); // 璁剧疆 璇锋眰澶寸殑缂栫爜鏍煎紡涓� UTF-8 鐩殑鏄繚璇佸悗缁� 琛ㄥ崟涓殑涓枃鑳藉姝ｅ父鑾峰彇
		//upload.setFileSizeMax(1024*1024); // 璁剧疆 涓婁紶鐨勬椂鍊� 鍗曚釜鏂囦欢鏈�澶уぇ灏� 鍗曚綅 瀛楄妭
		//upload.setSizeMax(1024*1024); // 璁剧疆 涓�涓〃鍗曚腑 鎬荤殑涓婁紶鏂囦欢澶у皬 鍗曚綅 瀛�
		if(upload.isMultipartContent(request)) { //鍒ゆ柇 杩欎釜琛ㄥ崟鏄笉鏄竴涓� 鏂囦欢涓婁紶琛ㄥ崟 锛堝垽鏂〃鍗曢噷鏈夋病鏈� enctype="multipart/form-data"锛�
			try {
				String teamName = null;
				String teamRegion = null;
				String teamCoach = null;
				String teamStadium = null; 
				int unionId = 0; 
				int partitionId = 0; //鐢ㄤ簬鎺ユ敹 鐢ㄦ埛鍙戣繃鏉ョ殑璇锋眰褰撲腑 鏂囨湰鍙傛暟
				String fileName = null;
				List<FileItem> items = upload.parseRequest(request); // 鏍稿績瀵硅薄鎶� 璇锋眰涓殑 鍙傛暟(鏂囨湰銆佹枃浠�) 杞崲鎴愪竴涓� FileItem闆嗗悎
				for(FileItem item : items) {//閬嶅巻鎵�鏈� 缁勪欢
					
					if(item.isFormField()) { //鍒ゆ柇鍙栧嚭鐨勭粍浠舵槸鍚︽槸鏂囨湰
//						System.out.println(item.getFieldName());//鑾峰彇缁勪欢鍦ㄨ〃鍗曚腑name灞炴�х殑鍊�
//						System.out.println(item.getName());//鏂囨湰鏃犳晥
//						System.out.println(item.getContentType());//鏂囨湰鏃犳晥
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
						if("teamName".equals(item.getFieldName())) {
							teamName = item.getString("UTF-8");
						}
						if("teamRegion".equals(item.getFieldName())) {
							teamRegion = item.getString("UTF-8");
						}
						if("teamCoach".equals(item.getFieldName())) {
							teamCoach = item.getString("UTF-8");
						}
						if("teamStadium".equals(item.getFieldName())) {
							teamStadium = item.getString("UTF-8");
						}
						if("unionName".equals(item.getFieldName())) {
							String unionName = item.getString("UTF-8");
							UnionDao ud = new UnionDaoImpl();
							unionId = ud.selectUnionId(unionName).getUnionId();
						}
						if("partitionName".equals(item.getFieldName())) {
							String partitionName = item.getString("UTF-8");
							PartitionDao pd = new PartitionDaoImpl();
							partitionId = pd.selectPartitionId(partitionName).getPartitionId();
						}
					}else {//涓嶆槸缁勪欢锛屾槸涓�涓枃浠�
						
//						System.out.println(item.getName());//鑾峰彇鐢ㄦ埛涓婁紶鏂囦欢鐨� 鍘熷鏂囦欢鍚嶅瓧
//						System.out.println(item.getContentType());//鑾峰彇 鐢ㄦ埛涓婁紶鏂囦欢鐨勭被鍨� contentType
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
//						System.out.println(item.getSize()) ;鑾峰彇 涓婁紶鏂囦欢鐨勫ぇ灏�
//						InputStream ins = item.getInputStream();//鑾峰彇 涓婁紶鏂囦欢璇诲彇鐨勮緭鍏ユ祦锛岀敤浜庤鐢ㄦ埛涓婁紶鐨勬枃浠讹紝鎵嬪姩澶嶅埗
//						String realPath = req.getServletContext().getRealPath("userImg");// 鑾峰彇椤圭洰璺緞涓� 鏌愪釜鏂囦欢澶圭殑 鐪熷疄璺緞銆佹妸鏂囦欢瀛樺湪 椤圭洰璺緞涓�
						//甯屾湜 鎶婄▼搴� 鍜� 涓婁紶鐨勬枃浠跺垎寮�锛屾妸鏂囦欢 椤圭洰璺緞涔嬪(涓嶆斁鍦╰omcat閲�)
						String realPath = "C://nba/images/team";
						File folder = new File(realPath);//鍥剧墖淇濆瓨鍦� 鏈嶅姟鍣ㄧ殑鏌愪釜鐪熷疄鍦板潃(涓嶆斁鍦ㄩ」鐩矾寰勪笅)
						if(!folder.exists()) {
							folder.mkdirs();
						}
						// 鑾峰彇 涓�涓敮涓�鐨勬枃浠� 鍚嶅瓧(UUID,鏃堕棿 鎴�)+鏂囦欢鐨勫悗缂�鍚�
						fileName = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
						// 璁剧疆 鏈�缁堝鍒舵枃浠剁殑鏂囦欢璺緞
						File desFile = new File(realPath,fileName);
						/*
						 * 鎵嬪姩澶嶅埗鏂囦欢
						 * OutputStream ops = new FileOutputStream(desFile); int a = -1;
						 * while((a=ins.read())!=-1) { ops.write(a); } ops.flush(); ins.close();
						 */
						item.write(desFile);//鍒╃敤item鎻愪緵鐨勬柟娉曡繘琛屽鍒�
						
					}
//					
				}
				
				//璁剧疆 鏁版嵁搴撻噷瀛樺偍鐨� 涔︾殑璺緞
				String virutalPath = "/nba/images/team/"+fileName;
				Team team = new Team(teamId, teamName, teamRegion, virutalPath, teamCoach, teamStadium, unionId, partitionId);
				ts.updateTeam(team);
				response.sendRedirect("SearchServlet.do");
			} catch (FileUploadException e) {

				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("涓嶆槸鏂囦欢涓婁紶琛ㄥ崟");
		}

	}
	public void search(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String keyword =request.getParameter("keyword");
		int pageNum,pageSize;
		if(keyword == null) {
			keyword = "";
		}
		if(request.getParameter("pageNum") == null) {
			pageNum = 1;
		}else {
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
		}
		
		if(request.getParameter("pageSize") == null) {
			pageSize = 10;
		}else {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		TeamService teamservice = new TeamServiceImpl();
		request.setAttribute("team", teamservice.getTeam(keyword, pageNum, pageSize));
		response.sendRedirect("bghome.jsp");
	}
	public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
	
		FileItemFactory itemFactory = new DiskFileItemFactory();//鍒涘缓涓�涓笂浼犳枃浠跺伐鍘傜被
		ServletFileUpload upload = new ServletFileUpload(itemFactory); //鍒涘缓涓�涓� 鏂囦欢涓婁紶 鏍稿績瀵硅薄
		upload.setHeaderEncoding("UTF-8"); // 璁剧疆 璇锋眰澶寸殑缂栫爜鏍煎紡涓� UTF-8 鐩殑鏄繚璇佸悗缁� 琛ㄥ崟涓殑涓枃鑳藉姝ｅ父鑾峰彇
		//upload.setFileSizeMax(1024*1024); // 璁剧疆 涓婁紶鐨勬椂鍊� 鍗曚釜鏂囦欢鏈�澶уぇ灏� 鍗曚綅 瀛楄妭
		//upload.setSizeMax(1024*1024); // 璁剧疆 涓�涓〃鍗曚腑 鎬荤殑涓婁紶鏂囦欢澶у皬 鍗曚綅 瀛�
		if(upload.isMultipartContent(req)) { //鍒ゆ柇 杩欎釜琛ㄥ崟鏄笉鏄竴涓� 鏂囦欢涓婁紶琛ㄥ崟 锛堝垽鏂〃鍗曢噷鏈夋病鏈� enctype="multipart/form-data"锛�
			try {
				String teamName = null;
				String teamRegion = null;
				String coach = null;
				String stadium = null; 
				int union = 0; 
				int partition = 0; //鐢ㄤ簬鎺ユ敹 鐢ㄦ埛鍙戣繃鏉ョ殑璇锋眰褰撲腑 鏂囨湰鍙傛暟
				String fileName = null;
				List<FileItem> items = upload.parseRequest(req); // 鏍稿績瀵硅薄鎶� 璇锋眰涓殑 鍙傛暟(鏂囨湰銆佹枃浠�) 杞崲鎴愪竴涓� FileItem闆嗗悎
				for(FileItem item : items) {//閬嶅巻鎵�鏈� 缁勪欢
					
					if(item.isFormField()) { //鍒ゆ柇鍙栧嚭鐨勭粍浠舵槸鍚︽槸鏂囨湰
//						System.out.println(item.getFieldName());//鑾峰彇缁勪欢鍦ㄨ〃鍗曚腑name灞炴�х殑鍊�
//						System.out.println(item.getName());//鏂囨湰鏃犳晥
//						System.out.println(item.getContentType());//鏂囨湰鏃犳晥
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
						if("addteamName".equals(item.getFieldName())) {
							teamName = item.getString("UTF-8");
						}
						if("addteamRegion".equals(item.getFieldName())) {
							teamRegion = item.getString("UTF-8");
						}
						if("addCoach".equals(item.getFieldName())) {
							coach = item.getString("UTF-8");
						}
						if("addStadium".equals(item.getFieldName())) {
							stadium = item.getString("UTF-8");
						}
						if("union".equals(item.getFieldName())) {
							String unionName = item.getString("UTF-8");
							UnionDao ud = new UnionDaoImpl();
							union = ud.selectUnionId(unionName).getUnionId();
						}
						if("partition".equals(item.getFieldName())) {
							String partitionName = item.getString("UTF-8");
							PartitionDao pd = new PartitionDaoImpl();
							partition = pd.selectPartitionId(partitionName).getPartitionId();
						}
					}else {//涓嶆槸缁勪欢锛屾槸涓�涓枃浠�
						
//						System.out.println(item.getName());//鑾峰彇鐢ㄦ埛涓婁紶鏂囦欢鐨� 鍘熷鏂囦欢鍚嶅瓧
//						System.out.println(item.getContentType());//鑾峰彇 鐢ㄦ埛涓婁紶鏂囦欢鐨勭被鍨� contentType
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
//						System.out.println(item.getSize()) ;鑾峰彇 涓婁紶鏂囦欢鐨勫ぇ灏�
//						InputStream ins = item.getInputStream();//鑾峰彇 涓婁紶鏂囦欢璇诲彇鐨勮緭鍏ユ祦锛岀敤浜庤鐢ㄦ埛涓婁紶鐨勬枃浠讹紝鎵嬪姩澶嶅埗
//						String realPath = req.getServletContext().getRealPath("userImg");// 鑾峰彇椤圭洰璺緞涓� 鏌愪釜鏂囦欢澶圭殑 鐪熷疄璺緞銆佹妸鏂囦欢瀛樺湪 椤圭洰璺緞涓�
						//甯屾湜 鎶婄▼搴� 鍜� 涓婁紶鐨勬枃浠跺垎寮�锛屾妸鏂囦欢 椤圭洰璺緞涔嬪(涓嶆斁鍦╰omcat閲�)
						String realPath = "C://nba/images/team";
						File folder = new File(realPath);//鍥剧墖淇濆瓨鍦� 鏈嶅姟鍣ㄧ殑鏌愪釜鐪熷疄鍦板潃(涓嶆斁鍦ㄩ」鐩矾寰勪笅)
						if(!folder.exists()) {
							folder.mkdirs();
						}
						// 鑾峰彇 涓�涓敮涓�鐨勬枃浠� 鍚嶅瓧(UUID,鏃堕棿 鎴�)+鏂囦欢鐨勫悗缂�鍚�
						fileName = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
						// 璁剧疆 鏈�缁堝鍒舵枃浠剁殑鏂囦欢璺緞
						File desFile = new File(realPath,fileName);
						/*
						 * 鎵嬪姩澶嶅埗鏂囦欢
						 * OutputStream ops = new FileOutputStream(desFile); int a = -1;
						 * while((a=ins.read())!=-1) { ops.write(a); } ops.flush(); ins.close();
						 */
						item.write(desFile);//鍒╃敤item鎻愪緵鐨勬柟娉曡繘琛屽鍒�
						
					}
//					
				}
				
				//璁剧疆 鏁版嵁搴撻噷瀛樺偍鐨� 涔︾殑璺緞
				String virutalPath = "/nba/images/team/"+fileName;
				Team team = new Team(teamName, teamRegion, virutalPath, coach, stadium, union, partition);
				TeamService ts  = new TeamServiceImpl();
				ts.addTeam(team);
				resp.sendRedirect("SearchServlet.do");
			} catch (FileUploadException e) {

				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("涓嶆槸鏂囦欢涓婁紶琛ㄥ崟");
		}
	}
}

